'use strict';

const Controller = require('egg').Controller;

class AdminController extends Controller {
  /*
   * 管理员列表
   **/
  async index() {
    const keyword = this.ctx.request.query.keywords;
    const condition = keyword ? { user_name: { [this.app.Sequelize.Op.like]: '%' + keyword + '%' } } : {};
    const page = this.ctx.request.query.page || 1;
    const res = await this.ctx.service.admin.pageList(condition, page);
    const admin_lists = res.rows;
    const admin_count = res.count;
    const role_list = await this.ctx.service.admin.getRoleList({});
    const lists = [];
    if (admin_lists && role_list) {
      const role_id_name = [];
      role_list.forEach(item => {
        role_id_name[item.role_id] = item.role_name;
      });
      admin_lists.forEach(item => {
        item.role = role_id_name[item.role_id];
        item.add_time = this.ctx.helper.time_to_date(item.add_time);// 时间戳转换
        lists.push(item);
      });
    }
    const html_page = await this.ctx.service.paginator.paginator(admin_count, page);
    const data_list = {
      lists,
      page: html_page,
      keyword,
    };
    await this.ctx.render(this.ctx.view_path(), data_list);
  }

  /*
   * 管理员的增改
   **/
  async info() {
    const ctx = this.ctx;
    const method = ctx.request.method;
    if (method === 'POST') {
      const user_name = ctx.request.body.user_name;
      const email = ctx.request.body.email;
      const password = ctx.request.body.password;
      const role_id = ctx.request.body.role_id;
      const act = ctx.request.body.act;
      let body = { status: 0, message: '操作失败' };
      if (act === 'add' && !ctx.helper.check_name(user_name)) {
        body.message = '用户名格式错误';
      } else if (!ctx.helper.check_email(email)) {
        body.message = '邮箱错误';
      } else if (act === 'add' && password.length < 6) {
        body.message = '密码长度不能低于6位';
      } else if (ctx.request.body.admin_id != ctx.session.admin_id && !role_id) {
        body.message = '参数错误';
      } else {
        switch (act) {
          case 'add':
          {
            const admin = await ctx.model.Admin.find({ where: { user_name }, raw: true });
            if (admin) {
              body.message = '用户名已存在';
            } else {
              const data = {
                user_name,
                email,
                password: ctx.helper.md5(ctx.helper.md5(password)),
                role_id,
                add_time: ctx.helper.date_to_time(),
              };
              const admin = await ctx.model.Admin.create(data, { raw: true });
              if (admin) body = { status: 1, message: '操作成功' };
            }
            break;
          }
          case 'edit':
          {
            const admin_id = ctx.request.body.admin_id;
            if (admin_id) {
              if (admin_id == 1 && admin_id != ctx.session.admin_id) {
                body.message = '无权对管理员进行编辑';
              } else {
                const data = { email, role_id };
                if (password) data.password = ctx.helper.md5(ctx.helper.md5(password));
                const res = await ctx.model.Admin.update(data, { where: { admin_id } });
                if (res[0]) body = { status: 1, message: '操作成功' };
              }
            } else {
              body.message = '参数错误';
            }
            break;
          }
          default:
            body.message = '参数错误';
            break;
        }
      }
      ctx.body = body;
      ctx.status = 200;
    } else {
      const id = ctx.request.query.id;
      let info = {};
      let act = 'add';
      if (id) {
        info = await ctx.model.Admin.findById(id, { raw: true });
        act = 'edit';
      }
      const role_list = await ctx.model.Adminrole.findAll({ attributes: [ 'role_id', 'role_name' ], raw: true });
      const data_list = {
        info,
        role_list,
        act,
      };
      await ctx.render(ctx.view_path(), data_list);
    }
  }

  /*
   * 角色列表
   **/
  async role() {
    const condition = {};
    const page = this.ctx.request.query.page || 1;
    const res = await this.ctx.service.admin.rolePageList(condition, page);
    const lists = res.rows;
    const count = res.count;
    const html_page = await this.ctx.service.paginator.paginator(count, page);
    const data_list = {
      lists,
      page: html_page,
    };
    await this.ctx.render(this.ctx.view_path(), data_list);
  }

  /*
   * 角色增改
   **/
  async role_info() {
    const ctx = this.ctx;
    const method = ctx.request.method;
    if (method === 'POST') {
      const role_data = ctx.request.body.data;
      const menu = ctx.request.body.menu;
      const act = ctx.request.body.act;
      const act_list = menu.join(',');
      const body = { status: 0, message: '操作失败' };
      if (!role_data.role_name) {
        body.message = '角色名必须';
      } else {
        switch (act) {
          case 'add':
          {
            const data = {
              role_name: role_data.role_name,
              act_list,
              role_desc: role_data.role_desc,
            };
            const role = await ctx.model.Adminrole.create(data, { raw: true });
            if (role) {
              body.message = '操作成功';
              body.status = 1;
            }
            break;
          }
          case 'edit':
          {
            const role_id = ctx.request.body.role_id;
            if (role_id) {
              if (role_id == 1) {
                body.message = '总管理员角色禁止编辑';
              } else {
                const data = {
                  role_name: role_data.role_name,
                  act_list,
                  role_desc: role_data.role_desc,
                };
                const res = await ctx.model.Adminrole.update(data, { where: { role_id } });
                if (res[0]) {
                  body.message = '操作成功';
                  body.status = 1;
                }
              }
            } else {
              body.message = '参数错误';
            }
            break;
          }
          default:
            body.message = '参数错误';
            break;
        }
      }
      ctx.body = body;
      ctx.status = 200;
    } else {
      const id = ctx.request.query.id;
      let info = {};
      let act = 'add';
      let act_list = '';
      if (id) {
        info = await ctx.model.Adminrole.findById(id, { raw: true });
        if (info) {
          act_list = info.act_list;
        }
        act = 'edit';
      }
      const menu_tree = await ctx.service.admin.getRoleMenuList(act_list);
      const data_list = {
        detail: info,
        act,
        menu_tree,
      };
      await ctx.render(ctx.view_path(), data_list);
    }
  }

  /*
   * 管理员日志
   **/
  async log() {
    const condition = {};
    const page = this.ctx.request.query.page || 1;
    const res = await this.ctx.service.admin.logPageList(condition, page);
    const log_lists = res.rows;
    const count = res.count;
    const html_page = await this.ctx.service.paginator.paginator(count, page);
    const lists = [];
    const admin_list = await this.ctx.model.Admin.findAll({ attributes: [ 'admin_id', 'user_name' ] }, { raw: true });
    for (const item of log_lists) {
      for (const admin of admin_list) {
        if (item.admin_id === admin.admin_id) {
          item.user_name = admin.user_name;
        }
      }
      lists.push(item);
    }
    const data_list = {
      lists,
      page: html_page,
    };
    await this.ctx.render(this.ctx.view_path(), data_list);
  }

  /*
   * 系统错误日志
   **/
  async errlog() {
    const condition = {};
    const page = this.ctx.request.query.page || 1;
    const res = await this.ctx.service.admin.errLogPageList(condition, page);
    const lists = res.rows;
    const count = res.count;
    const html_page = await this.ctx.service.paginator.paginator(count, page);
    const data_list = {
      lists,
      page: html_page,
    };
    await this.ctx.render(this.ctx.view_path(), data_list);
  }

  /*
   * 系统错误日志
   **/
  async dblog() {
    const condition = {};
    const page = this.ctx.request.query.page || 1;
    const res = await this.ctx.service.admin.dbLogPageList(condition, page);
    const lists = res.rows;
    const count = res.count;
    const html_page = await this.ctx.service.paginator.paginator(count, page);
    const data_list = {
      lists,
      page: html_page,
      admin_list: res.admin_list,
    };
    await this.ctx.render(this.ctx.view_path(), data_list);
  }

}

module.exports = AdminController;
